import { Elysia, t } from 'elysia'
import { cors } from '@elysiajs/cors'  // 引入官方 CORS 插件

// 定义任务类型
interface Task {
  id: number
  title: string
  completed: boolean
  createdAt: Date
}

// 模拟数据库
let tasks: Task[] = [
  { id: 1, title: '学习 Bun + Elysia', completed: false, createdAt: new Date() },
  { id: 2, title: '开发前端页面', completed: false, createdAt: new Date() }
]
let nextId = 3

const app = new Elysia()
  .use(cors())  // 使用官方 CORS 插件
  // 获取所有任务
  .get('/tasks', () => tasks)
  // 获取单个任务
  .get('/tasks/:id', ({ params }) => {
    const task = tasks.find(t => t.id === Number(params.id))
    return task ? task : { error: '任务不存在' }
  })
  // 创建任务
  .post('/tasks', ({ body }) => {
    const newTask: Task = {
      id: nextId++,
      title: body.title,
      completed: false,
      createdAt: new Date()
    }
    tasks.push(newTask)
    return newTask
  }, {
    body: t.Object({
      title: t.String()
    })
  })
  // 更新任务状态
  .patch('/tasks/:id', ({ params, body }) => {
    const index = tasks.findIndex(t => t.id === Number(params.id))
    if (index === -1) return { error: '任务不存在' }
    
    tasks[index].completed = body.completed
    return tasks[index]
  }, {
    body: t.Object({
      completed: t.Boolean()
    })
  })
  // 删除任务
  .delete('/tasks/:id', ({ params }) => {
    const initialLength = tasks.length
    tasks = tasks.filter(t => t.id !== Number(params.id))
    return initialLength > tasks.length 
      ? { success: true } 
      : { error: '任务不存在' }
  })
  .listen(3333)

console.log(`后端服务运行在 http://${app.server?.hostname}:${app.server?.port}`)
    